'use strict';

//promise
function testPromise()
{
    var logging = document.getElementById('test-promise-log');
    function log(s)
    {
        var p = document.createElement('p');
        p.innerHTML = s;
        logging.appendChild(p);
    }
    while(logging.children.length > 1) 
    {
        logging.removeChild(logging.lastElementChild);
    }
    new Promise(function(resolve, reject) {
        log('start new Promise...');
        var timeOut = Math.random() * 2;
        log('set time to : ' + timeOut + ' seconds');
        setTimeout(function(){
            if(timeOut < 1)
            {
                log('call resolve()...');
                resolve('200 OK');
            }
            else{
                log('call reject()...');
                reject('timeout in ' + timeOut + ' seconds');
            }
        }, timeOut * 1000);
    })
    .then(function(result) { //on resolve
        log('success: ' + result);
    })
    .catch(function(reason) { // on reject
        log('fail: ' + reason);
    })
}

function testPromiseSerial()
{
    var logging = document.getElementById('test-promise-log2');
    while(logging.children.length > 1) 
    {
        logging.removeChild(logging.lastElementChild);
    }
    function log(s)
    {
        var p = document.createElement('p');
        p.innerHTML = s;
        logging.appendChild(p);
    }
    function multiply(input) 
    {
        return new Promise(function (resolve, reject) {
            log('calculating ' + input + ' x ' + input + '...');
            setTimeout(resolve, 500, input * input);
        });
    }
    function add(input)
    {
        return new Promise(function (resolve, reject) {
            log('calculating ' + input + ' + ' + input + '...');
            setTimeout(resolve, 500, input + input);
        });
    }

    var p = new Promise(function(resolve, reject) {
        log('start new Promise...');
        resolve(123);
    });

    p.then(multiply)
    .then(add)
    .then(multiply)
    .then(add)
    .then(function (result) {
        log('Got value: ' + result);
    });
}

function parallelPromise()
{
    var p1 = new Promise(function (resolve, reject) {
        setTimeout(resolve, 500, 'P1');
    });
    var p2 = new Promise(function (resolve, reject) {
        setTimeout(resolve, 600, 'P2');
    });
    // 同时执行p1和p2，并在它们都完成后执行then:
    Promise.all([p1, p2]).then(function (results) {
        console.log(results); // 获得一个Array: ['P1', 'P2']
    });
}


